<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class BookShelf extends Model
{
    //书架
    protected $table='bookshelf';

    protected $fillable=[
      'id',
      'is_opend',
      'book_id',
      'type',
      'created_at',
    ];

    public function book(){
        return $this->belongsTo(BookModel::class,'book_id','id');
    }

    public function my_bookshelf($user_id,$type,$key_work,$sort = ''){
        //查看是否是参与过活动
        $team = ActivityTeamUser::where('user_id',$user_id)->where('team_user_stash',1)->count();
        if($team>0){
            $query = $this->whereIn('is_opend',[1,2]);
        }else{
            $query = $this->where('is_opend',1);
        }
        //$query = $this->where('user_id',$user_id);
        if(!empty($type)){
            $query->where('type',$type);
        }

        if(!empty($sort)){
            $query->where('sort',$sort);
        }


        $data = $query ->with([
                'book'=>function($q)use($key_work){
                    if(empty($key_work)){
                        $q->select(['id','book_title','book_logo','author','synopsis','created_at']);
                    }else{
                        $q ->where('book_title','like','%'.$key_work.'%')
                            ->select(['id','book_title','book_logo','author','synopsis','created_at']);
                    }
                }
            ])
            ->paginate(15)->toArray();

        //处理下数据 不太合理
        if(count($data['data'])>0){
            foreach ($data['data'] as $k=>$v){
                if(empty($v['book'])){
                    unset($data['data'][$k]);
                }
            }
        }
        $data['data'] = array_merge($data['data']);

        $user_register = BookShelfRegister::where('user_id',$user_id)->first();
        $is_register = 1;
        if(empty($user_register)){
            $is_register = 2;
        }
        $data['is_register'] = $is_register;

        return $data;
    }

}
